#include "Sombras.h"


Sombras::Sombras() : m_textureID(0)
{
}


Sombras::~Sombras(){
	if (this->m_textureID != 0) {
		glDeleteTextures( 1, &(this->m_textureID) );
	}
}


void Sombras::cargarMapaSombras(std::string pathMapa) {
	// Carga el archivo de texturas
	int img_witdh;
	int img_height;
	int img_channels;
	unsigned char* image_buffer = SOIL_load_image(pathMapa.c_str(), &img_witdh, &img_height, &img_channels, SOIL_LOAD_RGBA);

	// Genera un ID para la textura
	glActiveTexture(GL_TEXTURE3);
	glGenTextures(1, &this->m_textureID);

	glBindTexture(GL_TEXTURE_2D, this->m_textureID);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img_witdh, img_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_buffer);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

	// Borra la imagen de la memoria, ya esta cargada en la placa de video
	SOIL_free_image_data( image_buffer );
}


GLuint Sombras::getTextureID() const {
	return this->m_textureID;
}


void Sombras::sendShadowMap(GLuint locShadowDeph, GLuint locShadowMaps, const glm::mat4 &matShadowDeph) const {
	if (locShadowDeph < 0 || locShadowMaps < 0){
		throw std::runtime_error("No se puede cargar los elementos de sombras en el shaders");
	}

	glActiveTexture(GL_TEXTURE3);
	glBindTexture(GL_TEXTURE_2D, this->m_textureID);

	glUniform1i(locShadowMaps, 3);
	glUniformMatrix4fv(locShadowDeph, 1, GL_FALSE, &matShadowDeph[0][0]);
}

